<template>
    <div class="mamager">
        <div class="query-c">
        <Button type="info" @click="insert">添加</Button>
        用户昵称:<Input v-model="searchParam.name" placeholder="请输入查询内容" style="width: 200px" /> 
        <Button type="primary" icon="ios-search">搜索</Button>
        </div>
        <br>
        <Table border :columns="managerColumns" :data="managerList"></Table>
        <br>
        <Page :total="searchParam.total"  @on-change="pageChange"/>
        <!-- 添加/编辑 -->
        <Modal
        v-model="managerModalshow"
        title="添加/编辑"
        >
            <Form ref="managerForm" :model="managerForm" :rules="managerFormRules" :label-width="80">
                <FormItem label="名称" prop="name">
                    <Input type="text" v-model="managerForm.name"></Input>
                </FormItem>
                <FormItem label="账号" prop="account">
                    <Input type="text" v-model="managerForm.account"></Input>
                </FormItem>
                <FormItem label="密码" prop="password" v-if="isAdd">
                    <Input type="text" v-model="managerForm.password"></Input>
                </FormItem>
                <FormItem label="手机号" prop="mobile">
                    <Input type="text" v-model="managerForm.mobile"></Input>
                </FormItem>
                <FormItem label="头像" prop="profile">
                    <Upload action="/manager/index/upload" :before-upload="handleBeforeUpload" :on-success="handleSuccess">
                        <Button icon="ios-cloud-upload-outline" >上传</Button>
                    </Upload>
                    <img v-if="managerForm.profile" :src="managerForm.profile" class="avatar" >
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit('managerForm')">提交</Button>
                    <Button @click="handleReset('managerForm')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
    export default {
        data () {
            const validateAccount = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('Please enter your account'));
                }else if(!new RegExp(/^[A-Za-z]{1}[A-Za-z0-9_-]{3,15}$/).test(value)){
                    callback(new Error('必须是以字母开头，只能包含字母数字下划线和减号，4到16位'));
                }else{
                    callback();
                }
            };
            const validatePassword = (rule, value, callback) => {
                if(!this.isAdd){
                    callback();
                }else if (!value) {
                    callback(new Error('Please enter your password'));
                } else if (!new RegExp(/(?=^.{6,16}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*]).*$/).test(value)) {
                    callback(new Error('6-16位，,至少有一个数字，一个大写字母，一个小写字母和一个特殊字符，四个任意组合'));
                } else {
                    callback();
                }
            };
            const validateMobile = (rule, value, callback) => {
                if (!value && !new RegExp(/^1\d{10}$/).test(value)) {
                    return callback(new Error('手机号不正确'));
                } else {
                    callback();
                }
            };
            return {
                managerColumns: [
                    {
                        title: '用户名',
                        key: 'name',
                    },
                    {
                        title: '账号',
                        key: 'account'
                    },
                    {
                        title: '创建时间',
                        key: 'createDate'
                    },
                    {
                        title: '类型',
                        render: (h, params) => {
                            return h('span', params.row.role == 1 ? '超级管理员' : '管理员');
                        }
                    },
                    {
                        title: '手机',
                        key: 'mobile'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        render: (h, params) => {
                            let operate = [h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.update(params.index)
                                        }
                                    }
                                }, '修改')];
                            if(1 != params.row.role ){
                                operate.push(
                                    h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.delete(params.index)
                                        }
                                    }
                                    }, '删除')
                                )
                            }    
                            return h('div', operate);
                        }
                    }
                ],
                managerList: [],
                searchParam: {name: '', pageNum: 1, pageSize: 10, total: 0},
                isAdd: false,
                managerForm: {profile:''},
                managerModalshow: false,
                managerFormRules: {
                    name: [
                        { required: true, message: 'The name cannot be empty', trigger: 'blur' },
                        { type: 'string', max: 20, message: 'Introduce no more than 20 words', trigger: 'blur' }
                    ],
                    account: [
                        { required: true, validator: validateAccount, trigger: 'blur' }
                    ],
                    password: [
                        { required: this.isAdd, validator: validatePassword, trigger: 'change' }
                    ],
                    mobile: [
                        { validator: validateMobile, trigger: 'change' }
                    ],
                },
            }
        },
        mounted(){
            this.getManagerList()
        },
        methods: {
            insert(){
                this.isAdd = true
                this.managerModalshow = true
                this.managerForm = {}
            },
            update(index){
                console.log(this.managerList[index].id)
                this.isAdd = false
                this.managerModalshow = true
                this.managerForm = this.managerList[index]
                this.managerForm.password = ''
            },
            delete (index) {
                console.log(this.managerList[index].id)
                if(confirm('确定要删除?')){
                    this.$axios.post('/manager/manager/update/',{id: this.managerList[index].id, status: -1}).then(res => {
                        //console.log(res)
                        if(res.status){
                            this.$Message.success('删除成功!');
                            this.getManagerList()
                        }else{
                            this.$Message.error(res.message);
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }
            },
            pageChange(pageNum){
                this.searchParam.pageNum = pageNum
                this.getManagerList()
            },
            getManagerList(){
                let params = {
                    "pageSize": this.searchParam.pageSize,
                    "pageNum": this.searchParam.pageNum,
                    "conditions":[
                        {"key":"name","value":this.searchParam.name,"method":"like"},

                        {"key":"createDate","value":"createDate","method":"desc"}
                    ]
                }

                this.$axios.post('/manager/manager/queryList',params).then(res => {
                    //console.log(res)
                    if(res.status){
                        //alert(2)
                        this.managerList = res.data.records
                        this.searchParam.total = res.data.total
                    }else{
                        this.$Message.error(res.message);
                    }
                }).catch(error=>{
                    console.error(error)
                })
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let url = this.isAdd ? '/manager/manager/insert' : '/manager/manager/update'
                        this.$axios.post(url,this.managerForm).then(res => {
                            //console.log(res)
                            if(res.status){
                                this.$Message.success('操作成功');
                                this.getManagerList()
                            }else{
                                this.$Message.error(res.message);
                            }
                            this.managerModalshow = false    
                        }).catch(error=>{
                            console.error(error)
                        })
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            handleSuccess(res, file) {
                if(res.status){
                    this.managerForm.tempProfile = res.data
                    this.managerForm.profile = res.data
                }
            },
            handleBeforeUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                this.$Message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                this.$Message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
        }
    }
</script>
<style scoped>
.avatar{
    width: 60px;
}
</style>